<template>
  <div class="payment-view">
    <NavBar />
    <main class="container">
      <div class="payment-container">
        <div class="page-header">
          <h1>支付订单</h1>
          <p class="breadcrumb">
            <router-link to="/">首页</router-link> / 
            <router-link :to="`/book/${book.id}`">书籍详情</router-link> / 
            <span>支付订单</span>
          </p>
        </div>
        
        <div class="order-info">
          <!-- 显示订单中所有书籍 -->
          <div class="books-list">
            <div class="book-preview" v-for="(bookItem, index) in books" :key="index">
              <img :src="bookItem.cover || 'https://picsum.photos/seed/book1/300/400'" :alt="bookItem.title" class="book-cover">
              <div class="book-details">
                <h2>{{ bookItem.title }}</h2>
                <p class="book-author">{{ bookItem.author }}</p>
                <p class="book-condition">
                  <span class="condition-tag" :class="getConditionClass(bookItem.book_condition)">{{ bookItem.book_condition }}</span>
                </p>
                <p class="book-seller">卖家: {{ bookItem.seller }}</p>
                <p class="book-price">¥{{ bookItem.price }}</p>
              </div>
            </div>
          </div>
          
          <div class="price-summary">
            <div class="price-row">
              <span>书籍总价</span>
              <span class="price">¥{{ book_price }}</span>
            </div>
            <div class="price-row" v-if="selectedMethod === 'online'">
              <span>平台服务费</span>
              <span class="price">¥{{ service_charge }}</span>
            </div>
            <div class="price-row total">
              <span>应付总额</span>
              <span class="price">¥{{ last_money }}</span>
            </div>
          </div>
        </div>
        
        <div class="payment-methods">
          <h3>选择交易方式</h3>
          <div class="method-options">
            <div 
              class="method-card" 
              :class="{ active: selectedMethod === 'online' }"
              @click="selectedMethod = 'online'"
            >
              <div class="method-icon">💳</div>
              <div class="method-info">
                <h4>线上支付</h4>
                <p>通过平台在线完成支付，平台担保交易安全</p>
              </div>
            </div>
            
            <div 
              class="method-card" 
              :class="{ active: selectedMethod === 'offline' }"
              @click="selectedMethod = 'offline'"
            >
              <div class="method-icon">🤝</div>
              <div class="method-info">
                <h4>线下交易</h4>
                <p>与卖家当面交易，当面检查书籍后付款</p>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 线上支付选项 -->
        <div class="payment-details" v-if="selectedMethod === 'online'">
          <h3>支付方式</h3>
          <div class="payment-channels">
            <div 
              class="channel-card" 
              :class="{ active: selectedChannel === 'wechat' }"
              @click="selectedChannel = 'wechat'"
            >
              <div class="channel-icon">
                <img src="https://via.placeholder.com/50?text=微信" alt="微信支付">
              </div>
              <span>微信支付</span>
            </div>
            
            <div 
              class="channel-card" 
              :class="{ active: selectedChannel === 'alipay' }"
              @click="selectedChannel = 'alipay'"
            >
              <div class="channel-icon">
                <img src="https://via.placeholder.com/50?text=支付宝" alt="支付宝">
              </div>
              <span>支付宝</span>
            </div>
            
            <div 
              class="channel-card" 
              :class="{ active: selectedChannel === 'campus' }"
              @click="selectedChannel = 'campus'"
            >
              <div class="channel-icon">
                <img src="https://via.placeholder.com/50?text=校园卡" alt="校园卡">
              </div>
              <span>校园卡</span>
            </div>
          </div>
          
          <div class="form-group">
            <label for="remark">备注信息（选填）</label>
            <textarea id="remark" v-model="remark" rows="3" placeholder="可以添加关于交付的特殊说明"></textarea>
          </div>
          
          <div class="action-buttons">
            <button class="btn-pay" @click="proceedPayment" :disabled="!selectedChannel">
              立即支付
            </button>
            <button class="btn-cancel" @click="cancelPayment">
              取消
            </button>
          </div>
        </div>
        
        <!-- 线下交易选项 -->
        <div class="payment-details" v-if="selectedMethod === 'offline'">
          <h3>安排见面</h3>
          <div class="form-group">
            <label for="meetingLocation">交易地点</label>
            <select id="meetingLocation" v-model="meetingLocation">
              <option value="">请选择交易地点</option>
              <option value="library">图书馆门口</option>
              <option value="canteen">学生食堂</option>
              <option value="dormitory">宿舍楼下</option>
              <option value="classroom">教学楼</option>
              <option value="custom">自定义地点</option>
            </select>
          </div>
          
          <div class="form-group" v-if="meetingLocation === 'custom'">
            <label for="customLocation">自定义地点</label>
            <input type="text" id="customLocation" v-model="customLocationText" placeholder="请输入详细地点">
          </div>
          
          <div class="form-group">
            <label for="meetingTime">交易时间</label>
            <input type="datetime-local" id="meetingTime" v-model="meetingTime">
          </div>
          
          <div class="form-group">
            <label for="contactNumber">联系电话</label>
            <input type="tel" id="contactNumber" v-model="contactNumber" placeholder="请输入您的手机号码">
          </div>
          
          <div class="form-group">
            <label for="offlineRemark">备注信息（选填）</label>
            <textarea id="offlineRemark" v-model="remark" rows="3" placeholder="可以添加关于交易的特殊说明"></textarea>
          </div>
          
          <div class="action-buttons">
            <button 
              class="btn-arrange" 
              @click="arrangeOfflineMeeting" 
              :disabled="!meetingLocation || !meetingTime || !contactNumber"
            >
              预约交易
            </button>
            <button class="btn-cancel" @click="cancelPayment">
              取消
            </button>
          </div>
          
          <div class="safety-tips">
            <h4>安全交易提示</h4>
            <ul>
              <li>建议选择人流较多的公共场所进行交易</li>
              <li>交易前请先检查书籍品相是否符合描述</li>
              <li>避免私下转账，确认书籍后再支付</li>
              <li>如遇任何问题，可联系平台客服介入处理</li>
            </ul>
          </div>
        </div>
      </div>
    </main>
    
    <!-- 支付结果弹窗 -->
    <div class="payment-result" v-if="showPaymentResult">
      <div class="result-card">
        <div class="result-icon" :class="{ success: paymentSuccess }">
          <span v-if="paymentSuccess">✓</span>
          <span v-else>✗</span>
        </div>
        <h3>{{ paymentSuccess ? '支付成功' : '支付失败' }}</h3>
        <p>{{ paymentResultMessage }}</p>
        <div class="result-actions">
          <button class="btn-primary" @click="goToOrders" v-if="paymentSuccess">
            查看订单
          </button>
          <button class="btn-secondary" @click="closePamentResult">
            {{ paymentSuccess ? '返回首页' : '重试' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import NavBar from '../components/NavBar.vue'

const route = useRoute()
const router = useRouter()
const bookId = computed(() => Number(route.params.id) || 0)

// 支付方式
const selectedMethod = ref('online') // online 或 offline
const selectedChannel = ref('') // wechat, alipay, campus
const remark = ref('')

// 线下交易信息
const meetingLocation = ref('')
const customLocationText = ref('')
const meetingTime = ref('')
const contactNumber = ref('')

// 支付结果
const showPaymentResult = ref(false)
const paymentSuccess = ref(true)
const paymentResultMessage = ref('')

// 订单数据
const orderData = ref(null)
const books = ref([])
const book_price = ref(0)
const service_charge = ref(0)
const last_money = ref(0)

// 模拟书籍信息（当无订单数据时使用）
const book = ref({
  id: 1,
  title: '算法导论',
  author: 'Thomas H. Cormen',
  price: 78.5,
  seller: '张同学',
  newDegree: 9,
  cover: 'https://picsum.photos/seed/book1/300/400'
})

// 获取书籍状态的样式类
const getConditionClass = (condition) => {
  if (!condition) return 'good'
  
  switch(condition.toLowerCase()) {
    case '几乎全新':
    case '全新':
    case 'new':
      return 'new'
    case '品相良好':
    case 'good':
      return 'good'
    case '有使用痕迹':
    case 'used':
      return 'used'
    default:
      return 'good'
  }
}

// 计算服务费和总价
const serviceFee = computed(() => {
  return service_charge.value || parseFloat((book_price.value * 0.05).toFixed(2))
})

const totalPrice = computed(() => {
  if (selectedMethod.value === 'online') {
    return last_money.value || parseFloat((book_price.value + serviceFee.value).toFixed(2))
  }
  return book_price.value
})

onMounted(() => {
  // 获取生成的订单数据
  loadOrderData()
})

const loadOrderData = () => {
  try {
    // 从localStorage获取订单数据
    const storedOrderData = localStorage.getItem('pendingOrderData')
    
    if (storedOrderData) {
      // 解析订单数据
      orderData.value = JSON.parse(storedOrderData)
      console.log('订单数据:', orderData.value)
      
      // 更新页面数据
      if (orderData.value.books && orderData.value.books.length > 0) {
        books.value = orderData.value.books.map(book => {
          // 修复API返回的seller拼写错误
          if (book.serller && !book.seller) {
            book.seller = book.serller
          }
          return book
        })
        
        // 使用第一本书作为页面导航显示
        if (books.value[0]) {
          book.value = {
            id: bookId.value,
            title: books.value[0].title || '未知书名',
            author: books.value[0].author || '未知作者',
            price: books.value[0].price || 0,
            seller: books.value[0].seller || books.value[0].serller || '未知卖家',
            newDegree: getNewDegree(books.value[0].book_condition),
            cover: books.value[0].cover || 'https://picsum.photos/seed/book1/300/400'
          }
        }
      }
      
      // 更新价格信息
      book_price.value = orderData.value.book_price || 0
      service_charge.value = orderData.value.service_charge || 0
      last_money.value = orderData.value.last_money || 0
    } else {
      console.log('未找到订单数据，使用默认数据')
      // 如果没有订单数据，尝试获取书籍信息
      fetchBookDetails()
    }
  } catch (error) {
    console.error('加载订单数据失败:', error)
    // 如果解析失败，尝试获取书籍信息
    fetchBookDetails()
  }
}

// 根据书籍状态获取新旧程度
const getNewDegree = (condition) => {
  if (!condition) return 7
  
  const conditionLower = typeof condition === 'string' ? condition.toLowerCase() : '';
  
  if (conditionLower.includes('全新') || conditionLower === 'new') return 9
  if (conditionLower.includes('良好') || conditionLower === 'good') return 7
  if (conditionLower.includes('使用') || conditionLower === 'used') return 5
  
  return 7
}

const fetchBookDetails = () => {
  // 模拟从API获取书籍详情
  if (bookId.value) {
    // 这里应该发送请求获取真实数据
    // 目前使用模拟数据
  }
}

const proceedPayment = () => {
  // 模拟支付过程
  if (!selectedChannel.value) {
    alert('请选择支付方式')
    return
  }
  
  // 清除localStorage中的订单数据（支付完成后不再需要）
  localStorage.removeItem('pendingOrderData')
  
  // 显示加载状态
  const paymentLoading = true
  
  // 模拟API请求
  setTimeout(() => {
    // 假设90%的概率支付成功
    const success = Math.random() < 0.9
    
    showPaymentResult.value = true
    paymentSuccess.value = success
    paymentResultMessage.value = success
      ? '您已成功支付，卖家将尽快发货。'
      : '支付过程中遇到问题，请稍后再试或更换支付方式。'
  }, 1500)
}

const arrangeOfflineMeeting = () => {
  if (!meetingLocation.value || !meetingTime.value || !contactNumber.value) {
    alert('请填写完整的交易信息')
    return
  }
  
  // 模拟API请求
  setTimeout(() => {
    showPaymentResult.value = true
    paymentSuccess.value = true
    paymentResultMessage.value = '已成功预约线下交易，卖家将会与您联系确认详情。'
  }, 1000)
}

const cancelPayment = () => {
  if (confirm('确定要取消此次交易吗？')) {
    router.go(-1) // 返回上一页
  }
}

const goToOrders = () => {
  router.push('/transactions')
}

const closePamentResult = () => {
  if (paymentSuccess.value) {
    router.push('/')
  } else {
    showPaymentResult.value = false
  }
}
</script>

<style scoped>
.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem;
}

.payment-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 2rem;
}

.page-header {
  margin-bottom: 2rem;
}

.page-header h1 {
  font-size: 1.8rem;
  color: #1f2937;
  margin-bottom: 0.5rem;
}

.breadcrumb {
  color: #6b7280;
  font-size: 0.9rem;
}

.breadcrumb a {
  color: #3b82f6;
  text-decoration: none;
}

.breadcrumb a:hover {
  text-decoration: underline;
}

.order-info {
  display: flex;
  gap: 2rem;
  margin-bottom: 2rem;
  padding-bottom: 2rem;
  border-bottom: 1px solid #e5e7eb;
}

.books-list {
  flex: 3;
}

.book-preview {
  display: flex;
  gap: 1.5rem;
  margin-bottom: 1rem;
}

.book-cover {
  width: 120px;
  height: 160px;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.book-details {
  flex: 1;
}

.book-details h2 {
  font-size: 1.4rem;
  color: #1f2937;
  margin-bottom: 0.5rem;
}

.book-author {
  color: #6b7280;
  margin-bottom: 0.75rem;
}

.condition-tag {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.condition-tag.new {
  background-color: #dcfce7;
  color: #166534;
}

.condition-tag.good {
  background-color: #fef3c7;
  color: #92400e;
}

.condition-tag.used {
  background-color: #fee2e2;
  color: #991b1b;
}

.book-seller {
  margin-top: 0.75rem;
  color: #6b7280;
}

.book-price {
  margin-top: 0.75rem;
  color: #6b7280;
}

.price-summary {
  flex: 2;
  background-color: #f9fafb;
  padding: 1.5rem;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

.price-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 1rem;
}

.price-row.total {
  border-top: 1px dashed #e5e7eb;
  margin-top: 0.5rem;
  padding-top: 1rem;
  font-weight: bold;
  font-size: 1.1rem;
}

.price {
  color: #ef4444;
}

.payment-methods {
  margin-bottom: 2rem;
}

.payment-methods h3, .payment-details h3 {
  font-size: 1.2rem;
  color: #1f2937;
  margin-bottom: 1rem;
}

.method-options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1rem;
}

.method-card {
  display: flex;
  gap: 1rem;
  padding: 1.5rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.method-card:hover {
  border-color: #3b82f6;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.method-card.active {
  border-color: #3b82f6;
  background-color: #eff6ff;
}

.method-icon {
  font-size: 2rem;
}

.method-info h4 {
  margin-bottom: 0.5rem;
  font-weight: 600;
}

.method-info p {
  color: #6b7280;
  font-size: 0.9rem;
}

.payment-channels {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.channel-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 100px;
}

.channel-card:hover {
  border-color: #3b82f6;
}

.channel-card.active {
  border-color: #3b82f6;
  background-color: #eff6ff;
}

.channel-icon {
  margin-bottom: 0.5rem;
}

.channel-icon img {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #374151;
}

input[type="text"],
input[type="tel"],
input[type="datetime-local"],
select,
textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 1rem;
}

input:focus,
select:focus,
textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.action-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
  margin-top: 2rem;
}

.btn-pay, .btn-arrange {
  padding: 0.75rem 2rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-pay:hover, .btn-arrange:hover {
  background-color: #2563eb;
}

.btn-pay:disabled, .btn-arrange:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.btn-cancel {
  padding: 0.75rem 2rem;
  background-color: white;
  color: #4b5563;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-weight: 500;
  font-size: 1rem;
  cursor: pointer;
}

.btn-cancel:hover {
  background-color: #f3f4f6;
}

.safety-tips {
  margin-top: 2rem;
  padding: 1.5rem;
  background-color: #fffbeb;
  border-radius: 8px;
  border-left: 4px solid #f59e0b;
}

.safety-tips h4 {
  margin-bottom: 0.75rem;
  color: #92400e;
  font-weight: 600;
}

.safety-tips ul {
  padding-left: 1.5rem;
  color: #92400e;
}

.safety-tips li {
  margin-bottom: 0.5rem;
}

.payment-result {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.result-card {
  background-color: white;
  border-radius: 8px;
  padding: 2.5rem;
  max-width: 400px;
  width: 90%;
  text-align: center;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.result-icon {
  width: 80px;
  height: 80px;
  margin: 0 auto 1.5rem;
  background-color: #fee2e2;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.5rem;
  color: #ef4444;
}

.result-icon.success {
  background-color: #dcfce7;
  color: #10b981;
}

.result-card h3 {
  font-size: 1.5rem;
  margin-bottom: 0.75rem;
  color: #1f2937;
}

.result-card p {
  color: #6b7280;
  margin-bottom: 2rem;
}

.result-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.btn-primary {
  padding: 0.75rem 1.5rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
}

.btn-primary:hover {
  background-color: #2563eb;
}

.btn-secondary {
  padding: 0.75rem 1.5rem;
  background-color: white;
  color: #4b5563;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
}

.btn-secondary:hover {
  background-color: #f3f4f6;
}

@media (max-width: 768px) {
  .container {
    padding: 1rem;
  }
  
  .payment-container {
    padding: 1.5rem;
  }
  
  .order-info {
    flex-direction: column;
    gap: 1.5rem;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .btn-pay, .btn-arrange, .btn-cancel {
    width: 100%;
  }
}
</style> 